/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.pay.handler.impl;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.bblocks.enums.SysEnum;
import com.bblocks.exception.ServiceException;
import com.bblocks.util.ServletUtils;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import com.pig4cloud.pigx.pay.entity.DTO.PayParamsDTO;
import com.pig4cloud.pigx.pay.entity.PayChannel;
import com.pig4cloud.pigx.pay.entity.PayTradeOrder;
import com.pig4cloud.pigx.pay.mapper.PayTradeOrderMapper;
import com.pig4cloud.pigx.pay.service.PayChannelService;
import com.pig4cloud.pigx.pay.service.PayTradeOrderService;
import com.pig4cloud.pigx.pay.utils.ChannelPayApiConfigKit;
import com.pig4cloud.pigx.pay.utils.PayChannelNameEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author lengleng
 * @date 2019-05-31
 * <p>
 * 微信公众号、小程序支付
 */
@Slf4j
@Service("WEIXIN_MP")
@RequiredArgsConstructor
public class WeChatJsapiPayOrderHandler extends AbstractPayOrderHandler {

	private final PayTradeOrderMapper tradeOrderMapper;
	private final PayChannelService payChannelService;
	private final HttpServletRequest request;
	private final PayTradeOrderService payTradeOrderService;
	/**
	 * 准备支付参数
	 * @return PayChannel
	 */
	@Override
	public PayChannel preparePayParams(Long tenantId) {
		PayChannel channel = payChannelService.getChannel(PayChannelNameEnum.WEIXIN_MP,tenantId);

		if (channel == null) {
			throw new IllegalArgumentException("微信jsapi支付渠道配置为空");
		}

		JSONObject params = JSONUtil.parseObj(channel.getParam());
		WxPayApiConfig wx = WxPayApiConfig.builder().appId(channel.getAppId()).mchId(channel.getChannelMchId())
				.partnerKey(params.getStr("partnerKey")).build();

		WxPayApiConfigKit.setThreadLocalWxPayApiConfig(wx);
		return channel;
	}

	public PayTradeOrder createTradeOrder(PayParamsDTO payInfo){
		PayTradeOrder tradeOrder = this.setTradeOrderBase(payInfo);

		payTradeOrderService.saveOne(tradeOrder);
		return tradeOrder;
	}

	/**
	 * 调起渠道支付
	 * @param tradeOrder 交易订单
	 */
	@Override
	public Object collection( PayTradeOrder tradeOrder) {
		/*String ip = ServletUtil.getClientIP(request);
		WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();

		// 预订单参数
		Map<String, String> params = UnifiedOrderModel.builder().appid(wxPayApiConfig.getAppId())
				.mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body(goodsOrder.getGoodsName())
				.attach(TenantContextHolder.getTenantId().toString())
				.out_trade_no(String.valueOf(tradeOrder.getOrderId())).total_fee(goodsOrder.getAmount())
				.spbill_create_ip(ip)
				.notify_url(ChannelPayApiConfigKit.get().getNotifyUrl() + "/admin/notify/wx/callbak")
				.trade_type(TradeType.JSAPI.getTradeType()).openid(goodsOrder.getUserId()).build()
				.createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

		String xmlResult = WxPayApi.pushOrder(false, params);
		log.info("微信统一下单返回 {}", xmlResult);
		Map<String, String> resultMap = WxPayKit.xmlToMap(xmlResult);
		String prepayId = resultMap.get("prepay_id");
		return WxPayKit.prepayIdCreateSign(prepayId, wxPayApiConfig.getAppId(), wxPayApiConfig.getPartnerKey(),
				SignType.HMACSHA256);*/
		throw new ServiceException(SysEnum.ERR_NO_REALIZE);
	}


	public Object pay(PayTradeOrder tradeOrder) throws IOException {
		String ip = ServletUtil.getClientIP(request);
		WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();

		// 预订单参数
		Map<String, String> params = UnifiedOrderModel
				.builder().appid(wxPayApiConfig.getAppId())
				.mch_id(wxPayApiConfig.getMchId())
				.nonce_str(WxPayKit.generateStr())
				.body(tradeOrder.getBody())
				.attach(formExtraParams(tradeOrder.getTenantId(),tradeOrder.getChannelId()))
				.out_trade_no(tradeOrder.getPayNo())
				.total_fee(tradeOrder.getAmount().toString())
				.spbill_create_ip(ip)
				.notify_url(ChannelPayApiConfigKit.get().getNotifyUrl())
				.trade_type(TradeType.JSAPI.getTradeType())
				.openid(tradeOrder.getParam1()).build()
				.createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

		String xmlResult = WxPayApi.pushOrder(false, params);
		log.info("微信jsapi统一下单返回 {}", xmlResult);
		Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

		String return_code = result.get("return_code");
		String return_msg = result.get("return_msg");
		if (!WxPayKit.codeIsOk(return_code)) {
			throw new RuntimeException(return_msg);
		}
		String result_code = result.get("result_code");
		if (!WxPayKit.codeIsOk(result_code)) {
			throw new ServiceException(SysEnum.SYS_ERROR.getCode(),"支付系统故障，请稍后再试!");
		}
		// 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		String prepayId = result.get("prepay_id");

		Map<String, String> packageParams = WxPayKit.prepayIdCreateSign(prepayId, wxPayApiConfig.getAppId(),
				wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

		String jsonStr = JSON.toJSONString(packageParams);
		return jsonStr;
	}
}
